package com.chuangjian.hire.users.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.chuangjian.hire.users.service.CacheService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: RedisCacheServiceImpl
 * @Description:
 * @Author zhujunjie
 * @Date 2018/11/03 14:48
 * @Copyright (C) 杭州典击科技有限公司
 */
@Service("redisCacheService")
public class RedisCacheServiceImpl implements CacheService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void setCache(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    @Override
    public void setCache(String key, Object object) {
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(object));
    }

    @Override
    public String getCache(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    @Override
    public void setCacheForTimeOut(String key, String value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, value, time, unit);
    }

    @Override
    public void setCacheForTimeOut(String key, Object object, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(object), time, unit);
    }

    @Override
    public Boolean deleteCache(String key) {
        return stringRedisTemplate.delete(key);
    }

    @Override
    public Set<String> getCacheListByKeys(String key) {
        return stringRedisTemplate.keys(key);
    }

    @Override
    public Integer getCacheForInt(String key) {
        String str = stringRedisTemplate.opsForValue().get(key);
        return Convert.toInt(str, 0);
    }
}
